package github.sf.fw.tools.db;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * 原生的JDBC datasource
 *
 * @author zhoup
 * @since 2023/6/20
 */
public class JDBCDataSource implements DataSource {
    private final DSProperty dsProperty;

    public JDBCDataSource(DSProperty dsProperty) {
        this.dsProperty = dsProperty;
    }

    private Properties dsPropertiesConvert() {
        Properties properties = new Properties();
        properties.putAll(dsProperty.getMeta());
        properties.put("user", dsProperty.getUsername());
        properties.put("password", dsProperty.getPassword());
        return properties;
    }

    @Override
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(dsProperty.getUrl(), dsPropertiesConvert());
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return DriverManager.getConnection(dsProperty.getUrl(), username, password);
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        try {
            return iface.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
